import 'package:BeeApp/MainPage/MainChangeiPhonePage.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:permission_handler/permission_handler.dart';

// ignore: must_be_immutable
class MainNewsChangePage extends StatefulWidget {
  MainNewsChangePage({Key key}) : super(key: key);

  @override
  _MainNewsChangePageState createState() => _MainNewsChangePageState();
}

class _MainNewsChangePageState extends State<MainNewsChangePage> {
  final nameText = TextEditingController();
  List<Asset> images = List<Asset>();
  int chooseType = 1;
  String imageUrl = '';

  @override
  void initState() {
    super.initState();
    setState(() {
      nameText.text = getData("nickname");
      chooseType = int.parse(getData("sex"));
      print(chooseType.toString());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: getAppBar(context, "个人信息"),
      body: ListView(
        children: <Widget>[
          topView(),
          SizedBox(height: 10),
          nameView(),
          SizedBox(height: 10),
          chooseView(),
          SizedBox(height: 10),
          changeiPhone(),
          SizedBox(height: 10),
          btnView(),
        ],
      ),
    );
  }

  Widget topView() {
    return Container(
      color: Colors.white,
      padding: EdgeInsets.all(10),
      child: Column(
        children: <Widget>[
          InkWell(
            child: ClipOval(
              child: Container(
                height: setHeight(100),
                width: setHeight(100),
                child: showimage(0),
              ),
            ),
            onTap: () async {
              if (await Permission.camera.request().isGranted &&
                  await Permission.photos.request().isGranted) {
                await loadAssets();
                print('权限申请通过');
              } else {
                showToast('请前往设置，打开相机权限');
              }
            },
          ),
          Text(
            "请上传个人真实头像",
            style: TextStyle(
              color: Color(0xFF999999),
              fontSize: setFontSize(24),
            ),
          ),
        ],
      ),
    );
  }

  // 获取相册图片
  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    String error = 'No Error Dectected';

    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: 1,
        enableCamera: true,
        selectedAssets: images,
        materialOptions: MaterialOptions(
          startInAllView: true,
          allViewTitle: "所有照片",
          actionBarColor: "#abcdef",
          textOnNothingSelected: "请选择图片",
          selectionLimitReachedText: "最多选择1张图片",
        ),
      );
    } on Exception catch (e) {
      error = e.toString();
      print("aaaaa" + error);
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    setState(() {
      images = resultList;
      // _error = error;
    });
  }

  Widget showimage(int index) {
    if (images.length == 0) {
      return Container(
        child: CachedNetworkImage(
            imageUrl: getData("avatar"),
            height: setHeight(100),
            width: setHeight(100),
            fit: BoxFit.cover),
      );
    } else {
      Asset asset = images[index];
      return AssetThumb(
        asset: asset,
        width: 300,
        height: 300,
      );
    }
  }

  Widget nameView() {
    return Container(
      padding: EdgeInsets.fromLTRB(
        setWidth(30),
        setHeight(20),
        setWidth(30),
        setHeight(20),
      ),
      color: Colors.white,
      child: Row(
        // mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            "昵称",
            style: TextStyle(fontSize: setFontSize(32)),
          ),
          Expanded(
              child: TextField(
            controller: nameText,
            textAlign: TextAlign.end,
            cursorColor: Colors.grey[400],
            //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入昵称",
                hintStyle: TextStyle(
                    fontSize: setFontSize(30), color: Color(0xFFAEAEAE))),
            style:
                TextStyle(fontSize: setFontSize(30), color: Color(0xFFAEAEAE)),
          )),
        ],
      ),
    );
  }

  Widget chooseView() {
    return Container(
      padding: EdgeInsets.fromLTRB(
        setWidth(30),
        setHeight(20),
        setWidth(30),
        setHeight(20),
      ),
      color: Colors.white,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(
            "性别",
            style: TextStyle(fontSize: setFontSize(32)),
          ),
          Row(children: <Widget>[
            chooseSex(1),
            SizedBox(width: setWidth(70)),
            chooseSex(2),
          ]),
        ],
      ),
    );
  }

  Widget chooseSex(int index) {
    return InkWell(
      child: Row(
        children: <Widget>[
          Text(
            index == 1 ? "男" : "女",
            style: TextStyle(
              fontSize: setFontSize(34),
            ),
          ),
          SizedBox(width: setWidth(10)),
          Image.asset(
            chooseType == index
                ? "images/MainSelectImage.png"
                : "images/MainNoneImage.png",
            height: setHeight(34),
          )
        ],
      ),
      onTap: () {
        setState(() {
          chooseType = index;
        });
      },
    );
  }

  Widget changeiPhone() {
    return InkWell(
      child: Container(
        padding: EdgeInsets.fromLTRB(
          setWidth(30),
          setHeight(20),
          setWidth(30),
          setHeight(20),
        ),
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text(
              "联系电话",
              style: TextStyle(fontSize: setFontSize(32)),
            ),
            Image.asset(
              "images/MainNextImage.png",
              height: setHeight(30),
            )
          ],
        ),
      ),
      onTap: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => MainChangeiPhonePage()),
        );
      },
    );
  }

  Widget btnView() {
    return Container(
        padding: EdgeInsets.all(20),
        child: InkWell(
          child: Container(
            height: 50,
            width: 800,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(10)),
                border: Border.all(color: Color(0xFFFF4E29), width: 1)),
            child: Text(
              "保存",
              style: TextStyle(
                color: Color(0xFFFF4E29),
                fontSize: setFontSize(32),
              ),
            ),
          ),
          onTap: () {
            print("object");
            if (images.length > 0) {
              upLoadImage();
            } else {
              upLoadNews();
            }
          },
        ));
  }

  void upLoadImage() {
    showLoading(context);
    DioUtils.postImageHttp(
      context,
      "common/uploads",
      images: images,
      onSuccess: (t) {
        print(t);
        dismissLoading(context);
        Map dic = Map.from(t);
        if (dic["code"] == 1) {
          imageUrl = dic["data"]["url"][0];
          upLoadNews();
        }
      },
      onError: (error) {
        dismissLoading(context);
      },
    );
  }

  void upLoadNews() {
    Map<String, dynamic> dic = Map();
    dic["token"] = getData("token");
    if (imageUrl.length > 0) {
      dic["avatar"] = imageUrl;
    }
    if (nameText.text.length > 0) {
      dic["nickname"] = nameText.text;
    }
    dic["sex"] = chooseType.toString();
    showLoading(context);
    DioUtils.postHttp(
      context,
      "Usercenter/profile",
      parameters: dic,
      onSuccess: (t) {
        print(t);
        dismissLoading(context);
        showToast(t["msg"]);
      },
      onError: (error) {
        dismissLoading(context);
        print(error);
      },
    );
  }
}
